package com.ja.openchat.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;

import com.amap.api.maps.MapsInitializer;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.data.RegisterVue;
import com.ja.openchat.databinding.ActivitySplashBinding;
import com.ja.openchat.http.HttpExClient;
import com.ja.openchat.http.HttpVueClient;
import com.ja.openchat.ui.main.PricayCallback;
import com.ja.openchat.ui.main.PrivacyDialog;
import com.ja.openchat.viewmodels.SplashViewModel;
import com.lxj.xpopup.XPopup;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;

import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import pub.devrel.easypermissions.EasyPermissions;

//启动页
public class SplashActivity extends BaseActivity<ActivitySplashBinding, SplashViewModel> implements EasyPermissions.PermissionCallbacks {


    public final static String[] PERMISSIONS_BASIC = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA
    };
    public static final int REQUEST_BASIC = 100;

    @Override
    public void setStatusBar() {
//        BarUtils.setStatusBarLightMode(this, false);
//        BarUtils.setStatusBarColor(this, Color.WHITE);
        ImmersionBar.with(this)
                .autoDarkModeEnable(true)
                .transparentStatusBar()
                .init();
        setStatusBarFullTransparent();
    }

    /**
     * 全透状态栏
     */
    protected void setStatusBarFullTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        if(!isTaskRoot()){
//            finish();
//            return;
//        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initParam() {
        super.initParam();
        // 延伸显示区域到刘海
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//        }
//        getWindow().setAttributes(lp);

        MapsInitializer.updatePrivacyShow(this, true, true);
        MapsInitializer.updatePrivacyAgree(this, true);
//        // 设置页面全屏显示
//        final View decorView = getWindow().getDecorView();
//        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_splash;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public void initView() {
        super.initView();
        viewModel.setActivty(this);
    }

    public static void start(Context activity) {
        start(activity, null, null);
    }

    public static void start(Context activity, String action, Bundle extras) {
        start(activity, action, extras, null);
    }


    public static void start(Context activity, String action, Bundle extras, Uri data) {
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(action)) {
            intent.setAction(action);
        }
        if (extras != null) {
            intent.putExtras(extras);
        }
        if (data != null) {
            intent.setData(data);
        }
        intent.setClass(activity, SplashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    public static final String KEY_PRICY = "is_pricy";

    @Override
    public void initData() {
        super.initData();
        viewModel.setIntent(getIntent());
        OuterShareActivity.isStartSplash = true;
        OuterShareActivity.isStartMain = false;
        TelegramManager.getTelegramManager().startIndex = SPUtils.getInstance().getInt(TelegramManager.SPU_START_INDEX, 0);
        viewModel.isPricayOk = SPUtils.getInstance().getBoolean(KEY_PRICY, false);
        if (viewModel.isPricayOk) {
            initAll();
        } else {
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .isDestroyOnDismiss(true)
                    .dismissOnBackPressed(false)
                    .enableDrag(false)
                    .asCustom(new PrivacyDialog(this, new PricayCallback() {
                        @Override
                        public void onCancleClick() {
                            finish();
                        }

                        @Override
                        public void onOkClick() {
                            viewModel.isPricayOk = true;
                            SPUtils.getInstance().put(KEY_PRICY, true);
                            initAll();
                        }
                    }))
                    .show();
        }
    }


    private void initAll() {
        //基本权限检查
        if (!EasyPermissions.hasPermissions(this, PERMISSIONS_BASIC)) {
            EasyPermissions.requestPermissions(this,
                    String.format(getString(R.string.permission_basic_tip), getString(R.string.app_name)),
                    REQUEST_BASIC, PERMISSIONS_BASIC);
        } else {
            load();

        }
    }

    @Override
    public SplashViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(SplashViewModel.class);
    }

    private void load() {
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                //重新初始化
                TelegramManager.getTelegramManager().reInitTdlib();
                if (TelegramManager.getTelegramManager().getTgData().getUserState() == TelegramManager.GoUserState.GoUserState_TdlibParameters) {
                    viewModel.configTd();
                } else if (TelegramManager.getTelegramManager().getTgData().getUserState() == TelegramManager.GoUserState.GoUserState_Ready) {
                    viewModel.checkToJump();
                } else {
                    //
                }
            }
        }, 200);
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        load();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        new AlertDialog.Builder(this)
                .setMessage(String.format(getString(R.string.permission_basic_denied), getString(R.string.app_name)))
                .setPositiveButton(getString(R.string.exit), (dialog, which) -> {
                    dialog.dismiss();
                    Log.d("startsplash", "onPermissionsDenied finish");
                    finish();
                })
                .create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,
                permissions, grantResults, this);
    }

}
